<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/common/taglibs.jsp" %>
<!DOCTYPE html>
<html>
<head>
	<title>iDesigner</title>
	<%@ include file="/common/meta.jsp" %>
	<%--代码编辑器样式  2019/8/16--%>
	<style type="text/css">
		.CodeMirror { border: 1px solid silver; }
		.CodeMirror-empty { outline: 1px solid #c22; }
		.CodeMirror-empty.CodeMirror-focused { outline: none; }
		.CodeMirror pre.CodeMirror-placeholder { color: #999; }
	</style>
	<%--代码编辑器样式  2019/8/16--%>
	<script type="text/javascript">
        var codeMirrorEditor = null;
        var setting = {
			data: {
				simpleData: {
					enable: true
				
				}
			},
			callback: {
				onClick:initFunGrid,
			//	onDblClick: appendFunction
				onRightClick: appendFunction,
			//	onRename: saveZtreeModule
			//	onMouseUp:getTreeNode
			}
		};
	
	function initFunGrid(event, treeId, treeNode){
		var methodsName =treeNode.getParentNode().key;
		getFunctionGrid(methodsName,treeNode.key);
	}

	// 初始化代码编辑器
	function initCodeMirror(type) {
		var myTextarea = document.getElementById('functionText');
		codeMirrorEditor = CodeMirror.fromTextArea(myTextarea, {
			lineNumbers: true,
			mode: {name: type, globalVars: true},
			extraKeys: {"Ctrl-/": "autocomplete"},
			autofocus:true,
			theme: "idea",//编辑器主题
			//  快捷键
			scrollbarStyle: "overlay",
			//括号匹配
			matchBrackets: true,
			//代码折叠
			lineWrapping: true,
			foldGutter: true,
			gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
			placeholder: '请在此处输入代码'
		});
	}

	function appendFunction(event, treeId, treeNode){
		// var functions = treeNode.type;
		// $("#functionText").insert({"text":functions});
		if (treeId == "functionTree") {
			var functions = treeNode.type+";";
			console.log(functions)
			insertValue(functions);
		} else if (treeId == "eventTree") {
			$("#eventTree").data("delNode", treeNode);
			$("#eventTree").data("eventName", treeNode.name);
			$("#delEvent").menu('show', {
				left : event.pageX,
				top : event.pageY
			});
		}

	}
	function getFunction(type){
		 if(type=="eventType"){
			 
		 }else{
			 $("#funParam").html("<span style='font-size:10px;color:red'>若为主表字段则如下：[字段1key]+[字段2key]*[字段3key]<br/>若为子表字段则如下：[子表key.字段1key]+[子表key.字段2key]*[子表key.字段3key]</span><input  type='button' value='选择字段' onclick='getModlueInfo();'></input>");
			$("#catchSpan").html("");
		 }
		 // $("#functionText").val("");
        setFunParams("");
        setFunText("")
        setTimeout(function () {
            codeMirrorEditor.refresh()
        },1)
			var options = {
						url: "${ctx}/design/getFunction",
						success:function(data) {
							var ztreeJson =[];
							 $.each(data.msg.children,function(k,v){
								 var ch =[];
								var tree = {"name":v.caption,"key":v.key};
								 $.each(v.children,function(ck,cv){
									 var str = "";
									 $.each(cv.children,function(nk,nv){
										 str +=nv.key+",";
									 });
									var param = str.substring(0, str.length-1);
									var ch_fun = {"name":cv.key+"("+cv.caption+")","key":cv.key,"type":cv.key+"("+param+")"};
									ch.push(ch_fun);
									
								}); 
								tree["children"]=ch; 
								ztreeJson.push(tree);
							});
						 	$.fn.zTree.init($("#functionTree"),setting,ztreeJson );
						 	
							var treeObj = $.fn.zTree.getZTreeObj("functionTree");
							treeObj.expandAll(true);
						//	alert("1111");
						}
					};
				fnFormAjaxWithJson(options);
	
	};
	function getFunctionGrid(methodsName,methodName){
		var options = {
				url: "${ctx}/design/getFunction",
				success:function(data) {
					var str ="";
					 $.each(data.msg.children,function(k,v){
						 if(v.key==methodsName){
							 $.each(v.children,function(ck,cv){
								 var functionGrid = [];
								if(cv.key == methodName){
									//alert("描述："+cv.description+"</br>");
									str +="描述："+cv.description+"</br>";
									$.each(cv.children,function(nk,nv){
										//alert("参数:{"+nv.type+"}"+nv.key+" "+nv.caption+","+nv.description);
										str += "参数： {"+nv.type+"}"+nv.key+" "+nv.caption+","+nv.description+"</br>";
										var prop = {"key":nv.key,"caption":nv.caption,"type":nv.type,"description":nv.description};
										functionGrid.push(prop);
									});
									//alert("return:"+cv["returns"].type);
									//alert("返回值：{"+cv["returns"].type+"}"+cv["returns"].key+" "+cv["returns"].caption+","+cv["returns"].description);
									str +="返回值：{"+cv["returns"].type+"}"+cv["returns"].key+" "+cv["returns"].caption+","+cv["returns"].description+"</br>";
									$("#function_grid").edatagrid("loadData",functionGrid);
									$("#funHelp").html(str);
									//alert("length:"+functionGrid.length);
									//return functionGrid;
								}
								
							}); 
						 }
					});
				}
			};
		fnFormAjaxWithJson(options);
	}
//获得函数框值
function getFunText(){
	// return $("#functionText").val();
	return saveResult();
}

//设置函数框值
function setFunText(text){
	// $("#functionText").val(text);
    if(codeMirrorEditor) {
        var doc = codeMirrorEditor.getDoc();
        doc.setValue(text);
    }

}
function getFunParams() {
	return $("#funParams").text();
}
function setFunParams(param) {/*设置函数编辑界面function中的参数*/
	if(param != undefined && param != null) {
		$("#funParams").text(param);
	}	
}
/*打开选择字段弹窗*/
function getModlueInfo(){
	var module = window.parent.$.fn.module.getModule();
	var tables = module.dataSource.formList;
	$('#funFieldWin').window('open');
 	$("#modTables").combobox({
		"data" : tables,
		"valueField" : "key",
		"textField" : "caption",
		"onChange" : function(newVal, oldVal) {
			loadTableFields(newVal, tables);
		}
	}); 
}
//初始化公式选择字段的datagrid
function loadTableFields(tableKey, tables){
	var fieldsData = {
			"total" : 0,
			"rows" : []
	};
	for ( var i = 0; i < tables.length; i++) {
		if(tables[i].key==tableKey && tables[i].isMaster){
			$('#funFields').edatagrid({
				nowrap : true,
				striped : true,
				rownumbers : true,
				singleSelect : true,
				editIndex: -1,
				frozenColumns : [ [ {
					field : 'ck',
					checkbox : true
				} ] ],
				columns : [ [ {
					field : 'caption',
					title : '字段名',
					width : 120
				} ] ]
			});	
			var allfields = tables[i].fieldList;
			var realfields =[];
			for(var j = 0; j < allfields.length; j++){
				if(allfields[j].key){
					realfields.push(allfields[j]);
				}
			}
			fieldsData["rows"] = realfields;
			fieldsData["total"] = realfields.length;
			$('#funFields').data("isSub","");
			break;
		}else if(tables[i].key==tableKey){
			$('#funFields').edatagrid({
				nowrap : true,
				striped : true,
				rownumbers : true,
				singleSelect : true,
				editIndex: -1,
				frozenColumns : [ [ {
					field : 'ck',
					checkbox : true
				} ] ],
				columns : [ [ {
					field : 'caption',
					title : '字段名',
					width : 120
				}, {
					field : 'isTotal',
					title : '是否先求和再计算',
					width : 150,
					align : 'center',
					editor :{ 						
						"type":"checkbox",
						"options" : {
								"on":true,
								"off":false
							}
					}
				} ] ],
				onClickRow:function(rowIndex, rowData){
					$("#funFields").edatagrid("editRow", parseInt(rowIndex));
				}
			});
			var allfields = tables[i].fieldList;
			var realfields =[];
			for(var j = 0; j < allfields.length; j++){
				if(allfields[j].key){
					realfields.push(allfields[j]);
				}
			}
			fieldsData["rows"] = realfields;
			fieldsData["total"] = realfields.length;
			$('#funFields').data("isSub",tableKey);
			break;
		}
	}
	$('#funFields').edatagrid("loadData", fieldsData);
}
$(document).ready(function() {	
	$("#funFieldWin").window({
		width:420,
		height:300,
		onOpen: function() {
			$(this).window("move", {
				top:($(window).height()-370)*0.5,
				left:($(window).width()-430)*0.5
			});		
		},
		onClose:function() {		
			}
		});
	$("#_bt_query_").click(queryFunction);
	$("#_bt_reset_").click(function() {
		$("#keyWords").val("");
	});
	initCodeMirror("javascript");
});
//查询框
function queryFunction(){
	var queryValue = $("#keyWords").val();
	var treeObj = $.fn.zTree.getZTreeObj("functionTree");
	var allNodes = treeObj.getNodes();
	treeObj.cancelSelectedNode(); /*取消当前所有被选中节点的选中状态*/
	for(var i=0;i<allNodes.length;i++){
		var nodes  = allNodes[i].children;
		var len=nodes.length;
		for(var j=0;j<len;j++){
			var funName = nodes[j].name;
			var isSelect = funName.indexOf(queryValue);
			if(isSelect>-1){
				treeObj.selectNode(nodes[j],true);/*选中指定节点*/
				// break;
			}
		}
	}
}

//保存结果
function saveResult(){
	var result = "";
	if(codeMirrorEditor) {
		codeMirrorEditor.save();
		result = $("#functionText").val();
	}
	return result;
}

function insertValue(val) {
	if(codeMirrorEditor) {
		var doc = codeMirrorEditor.getDoc();
		doc.replaceSelection(val);
	}
}

//添加公式字段
function addFields(){
	var text ="";
	$('#funFields').edatagrid("saveRow");
	var fieldData = $('#funFields').edatagrid("getSelected");
	var subkey = $('#funFields').data("isSub");
	if(subkey){
		if(fieldData.isTotal=="true"){
			var type = fieldData.dataProperties.dataType;
			text ="["+subkey+"."+ fieldData.key+"."+type+"]";
		}else{
			text ="["+subkey+"."+ fieldData.key+"]";
		}
	}else{
		text ="["+fieldData.key+"]";
	}
	// $("#functionText").insert({"text":text});
	insertValue(text);
	$("#funFieldWin").window("close");
}
//在光标后插入文字的方法
(function($){ 
	$.fn.extend({"insert":function(value){ 
		value=$.extend({ "text":"[]" },value); 
		var dthis = $(this)[0]; //将jQuery对象转换为DOM元素 
		//IE下 
		if(document.selection){ 
			$(dthis).focus(); //输入元素textara获取焦点 
			var fus = document.selection.createRange();//获取光标位置 
			fus.text = value.text; //在光标位置插入值 
			$(dthis).focus(); ///输入元素textara获取焦点 
		} //火狐，google下标准 
		else if(dthis.selectionStart || dthis.selectionStart == '0'){ 
			var start = dthis.selectionStart; //获取焦点前坐标 
			var end =dthis.selectionEnd; //获取焦点后坐标 
			//以下这句，应该是在焦点之前，和焦点之后的位置，中间插入我们传入的值 .然后把这个得到的新值，赋给文本框 
			dthis.value = dthis.value.substring(0, start) + value.text + dthis.value.substring(end, dthis.value.length); 
		} 
		//在输入元素textara没有定位光标的情况 
		else{ 
			this.value += value.text; this.focus();
		}
		return $(this); 
	}}); 
})(jQuery);
</script>

</head>
<body  class="easyui-layout">
		<!-- <div fit="true" > -->
					<div region="east"  title="函数列表" style="width:350px;padding:1px;" collapsed="true">
						  	<div class="easyui-layout" fit="true" >
						 			<div region="north"  title="" split="true" style="height:200px;padding:1px;">
						 			<span>函数名:</span><input style="width:160px;height:12px;"type="text" name="keyWords" id="keyWords"></input>						
								<button type="button" id="_bt_query_">查询</button><button type="button" id="_bt_reset_">重置</button>
						 					<ul id="functionTree" class="ztree"></ul>
						 			</div>
						 			<div region="center"  title="参数" style="height:150px;padding:1px;">
										<table id="function_grid" style="width:auto;height:auto" class="easyui-datagrid"
											 singleSelect="true"
													fit="true">
											<thead>
												<tr>
													<th field="key" width="80" editor="{type:'validatebox'}">名称(key)</th>
													<th field="caption" width="80" editor="{type:'validatebox'}">简称(caption)</th>
													<th field="type" width="80" editor="{type:'validatebox'}">类型(type)</th>
													<th field="description" width="100" editor="{type:'validatebox'}">描述(Description)</th>
												</tr>
											</thead>
										</table>
						 			</div>  
						 			<div region="south" id="funHelp" title="帮助" split="true" style="height:100px;padding:1px;">
						 					
						 			</div>
						 	</div> 
					</div> 
					<div region="center"  title="函数编辑界面" style="padding:1px;">
						 <span id="funParam" style="font-size: 12pt">function(<span id="funParams"></span>)<br/>try{</span>
						 <textarea id="functionText" style="width:98%;height:92%"></textarea>
						 <span id="catchSpan" style="font-size: 12pt">}catch(e){alert(e);}</span>
						<%--底部提示  2019/8/16--%>
						 <div style="color:red;">注：ctrl+/ 可以自动提示关键字；ctrl+F 可以进行内容查找</div>
					</div>
					
	<div id="funFieldWin" class="easyui-window" title="选择字段" closed="true"
		modal="true" minimizable="false" maximizable="true"
		collapsible="false" closable="true"
		style=" padding: 5px;">
		<div class="easyui-layout" fit="true">
			<div region="center" border="false"
				style="padding: 3px; background: #fff; border: 1px solid #ccc;" >
				<div>
					<table border="0" cellpadding="0" cellspacing="1"
						class="table_form">
						<tr>
							<th style="width: 100px;"><label for="modTables">请选择表:</label>
							</th>
							<td><input id="modTables" style="width: 180px;"></input></td>
						</tr>
					</table>
					<div>
						<table id="funFields"></table>
					</div>
				</div>
			</div>
			<div region="south" border="false"
				style="height:31px;text-align: right; padding: 3px 0;" >
				<a class="easyui-linkbutton" href="javascript:void(0)"
					onclick="addFields();" >确定</a> 					
				<a class="easyui-linkbutton" href="javascript:void(0)"
					onclick="javascript:$('#funFieldWin').window('close');" >关闭</a>
			</div>
		</div>
	</div>
	<!-- </div> -->
</body>
</html>